package org.jeecg.modules.tigstatics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.JsonObject;
import org.jeecg.modules.tigstatics.entity.TigStatistics;
import org.jeecg.modules.tigstatics.mapper.TigStatisticsMapper;
import org.jeecg.modules.tigstatics.service.ITigStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 统计表
 * @Author: jeecg-boot
 * @Date:   2023-08-25
 * @Version: V1.0
 */
@Service
public class TigStatisticsServiceImpl extends ServiceImpl<TigStatisticsMapper, TigStatistics> implements ITigStatisticsService {
    @Autowired
    ITigStatisticsService iTigStatisticsService;

    private static final int MAX_QUERY_DAYS = 90;
    private static final int MIN_QUERY_DAYS = 1;

    /**
     * 获取指定天数的统计数据（90天内）
     * @param orgCode
     * @param days 指定天数
     * @return
     */
    @Override
    public Map<String,TigStatistics> getWarningCountBydays(String orgCode,int days){
        Map<String,TigStatistics> map = new LinkedHashMap();
        if(days > MAX_QUERY_DAYS)
            days = MAX_QUERY_DAYS;
        if (days < MIN_QUERY_DAYS)
            days = MIN_QUERY_DAYS;
        for(int i = 1; i <= days; i++){
            LambdaQueryWrapper<TigStatistics> wrapper = new LambdaQueryWrapper<>();
            //获取日期区间
            Date today = new Date();
            Calendar c = Calendar.getInstance();
            c.setTime(today);
            c.add(Calendar.DAY_OF_MONTH, -i);
            Date tarDate = c.getTime();//
            c.setTime(today);
            c.add(Calendar.DAY_OF_MONTH, -i + 1);
            Date tarDateNext = c.getTime();//
            //大于等于目标日期，少于后一天
            String strTarDate = new SimpleDateFormat("yyyy-MM-dd").format(tarDate);
            String strTarDateNext = new SimpleDateFormat("yyyy-MM-dd").format(tarDateNext);
            wrapper.eq(TigStatistics::getOrgCode,orgCode);
            //获取最新的一条记录
            wrapper.ge(TigStatistics::getCreateTime,strTarDate).lt(TigStatistics::getCreateTime,strTarDateNext).orderByDesc(TigStatistics::getCreateTime).last("limit 1");
            List<TigStatistics> list = iTigStatisticsService.list(wrapper);
            if (list.size() == 0)
                map.put(strTarDate,null);
            else {
                TigStatistics sta = list.get(0);
                map.put(strTarDate, sta);
            }
        }
        return map;
    }
}
